package com.bajiao.common.util;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * <P>
 * 用途:压缩图片
 * </p>
 *
 * @author: FanJq
 * @create: 2024-10-10
 **/
public class ImageZipUtil {

    /**
     * 压缩图片
     *
     * @param oldFile 要进行压缩的文件
     * @param newFile 新文件
     * @param quality 质量
     * @return 返回压缩后的文件的全路径
     */
    public static void zipImageFile(String oldFile, String newFile,float quality) {
        try {
            Thumbnails.of(oldFile)
                    .scale(1f)
                    .outputQuality(quality)
                    .toFile(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩图片
     *
     * @param picFile 要进行压缩的文件
     * @param quality 质量
     * @return
     */
    public static ByteArrayInputStream zipImageFile(MultipartFile picFile, float quality, String filename) {
        try {
            ByteArrayInputStream byteArrayInputStream = null;
            if(picFile.getSize() > 2 * 1024 * 1024){
                BufferedImage bufImg = ImageIO.read(picFile.getInputStream());
                //获取原图片的宽度、高度
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bufImg = Thumbnails.of(bufImg).scale(quality).asBufferedImage();
                ImageIO.write(bufImg,filename.substring(filename.lastIndexOf(".")+1),bos);
                byteArrayInputStream = new ByteArrayInputStream(bos.toByteArray());
            }else{
                byteArrayInputStream = new ByteArrayInputStream(picFile.getBytes());
            }
            return byteArrayInputStream;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
